//
//  YKCReconmendController.m
//  baisi
//
//  Created by 吴高烽 on 16/9/2.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKCReconmendController.h"
#import "YKRecommendCategoryCell.h"
#import "YKRecommendUserTableViewCell.h"
#import "YKRecommendCategory.h"
#import "YKRecommendUser.h"
#import <SVProgressHUD.h>
#import <AFNetworking.h>
#import <MJRefresh.h>
#define selectedCategory self.categories[self.categoryTableView.indexPathForSelectedRow.row]
@interface YKCReconmendController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong)NSArray<YKRecommendCategory*> *categories;
@property (nonatomic ,strong)NSArray<YKRecommendUser*> *users;
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
@property (weak, nonatomic) IBOutlet UITableView *userTableView;
// 右边关注用户的请求参数
@property (nonatomic ,strong)NSDictionary *param;
// AFN对象管理
@property (nonatomic ,strong)AFHTTPSessionManager *manager;

@end

@implementation YKCReconmendController
static NSString * const YKCategoryId = @"category";//user
static NSString * const YKUseryId = @"user";//user
-(AFHTTPSessionManager *)manager{
    if (_manager ==nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return  _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"推荐关注";
//    初始化控件
    [self setupUI];
//    添加刷新控件
    [self setupRefersh];
//    加载左侧的类别数据
    [self loadData];

}
/**
 *  集成刷新控件
 */
-(void)setupRefersh{
    self.userTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.userTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.userTableView.mj_footer.hidden = YES ;

}
-(void)setupUI{
    self.view.backgroundColor = YKGlobalBackgroundColor ;
    /**  xib 注册cell时使用该方法  */
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YKRecommendCategoryCell class]) bundle:nil] forCellReuseIdentifier:YKCategoryId];
    [self.userTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YKRecommendUserTableViewCell class]) bundle:nil] forCellReuseIdentifier:YKUseryId];
    self.categoryTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.userTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.userTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
  
}
// 加载左边的分类数据
-(void)loadData{
    __weak typeof(self) weakSelf = self;
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD show];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    [[AFHTTPSessionManager manager]GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //      隐藏指示器
        [SVProgressHUD dismiss];
        //        YKLog(@"object = %@",responseObject[@"list"]);
        weakSelf.categories = [YKRecommendCategory mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [weakSelf.categoryTableView reloadData];
        //        默认选中第一行
        [weakSelf.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
//        刷新第一行对应的关注用户数据，自动调用loadNewData方法
        [weakSelf.userTableView.mj_header beginRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败"];

    }];

}
// 加载右边的关注用户数据
-(void)loadMoreData{
     __weak typeof(self) weakSelf = self;
    YKRecommendCategory *c = selectedCategory;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"]= c.id;
    params[@"page"] = @(++c.currentPage) ;
//  保存最近一次的请求
    self.param = params ;
    [weakSelf.userTableView.mj_footer beginRefreshing];
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //        请求回调的block，如果不是最近一次的就return
        YKLog(@"object2 = %@",responseObject[@"list"]);
        NSArray *users = [YKRecommendUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [c.users addObjectsFromArray:users];
        if (weakSelf.param != params)  return ;
        [weakSelf.userTableView reloadData];
        [weakSelf checkFootState];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (weakSelf.param != params)  return ;
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败"];
        [weakSelf.userTableView.mj_footer endRefreshing] ;
    }];
}
-(void)loadNewData{
    __weak typeof(self) weakSelf = self;
    YKRecommendCategory *c = selectedCategory;
    c.currentPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"]=c.id;
    params[@"page"]= @(c.currentPage);
    self.param = params ;
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //        YKLog(@"object = %@",responseObject);
        NSArray *users =[YKRecommendUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [c.users removeAllObjects];
        [c.users addObjectsFromArray:users];
        c.total = responseObject[@"total"];
        if (weakSelf.param != params)  return ;
        //            刷新右边表格
        [weakSelf.userTableView reloadData];
        [weakSelf.userTableView.mj_header endRefreshing];
        [weakSelf checkFootState];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (weakSelf.param != params)  return ;
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败"];
        [weakSelf.userTableView.mj_header endRefreshing];
    }];
}
/**
 *  检测Foot的状态
 */
-(void)checkFootState{
    YKRecommendCategory *c = selectedCategory;
    //        控制每次刷新右边表格时的footView
    self.userTableView.mj_footer.hidden = (c.users.count==0);
    if (c.users.count==[c.total integerValue]) {
        [self.userTableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.userTableView.mj_footer endRefreshing] ;
    }

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.categoryTableView) return self.categories.count;
//   检测footer的状态
    [self checkFootState];
//        右边被选中类别的模型
        YKRecommendCategory *c = selectedCategory ;
        return  c.users.count;
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.categoryTableView) {
        YKRecommendCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:YKCategoryId];
        cell.category = self.categories[indexPath.row];
        return cell ;
    }else{
        YKRecommendUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YKUseryId];
        cell.user = [selectedCategory users][indexPath.row];
        return cell ;
    }
}
#pragma mark --UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//  每次点击前停止上次正在刷新的状态
    [self.userTableView.mj_footer endRefreshing];
    [self.userTableView.mj_header endRefreshing];
    
    YKRecommendCategory *c = self.categories[indexPath.row];
    if (c.users.count) {// 数据已加载
//     显示曾经的数据
        [self.userTableView reloadData];
    }else{// 第一加载数据
        [self.userTableView reloadData];//刷新页面，不再显示上一页的信息
        [self.userTableView.mj_header beginRefreshing];//会自动加载loadnewdata的方法
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
//    不进取消网络请求的操作，还会取消对应的block的内。当让还可以通过get返回的NSURLSessionDataTask对象来取消，[invalidateAndCancel]
    [self.manager.operationQueue cancelAllOperations];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end
